package com.sunxd.vue.infrastructure.utils;

import com.google.common.base.Throwables;
import com.sunxd.vue.bean.Response;
import com.sunxd.vue.domain.exception.InternalServerException;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 返回工具类
 */
@Slf4j
public class ResponseHelper {
    private ResponseHelper() {
    }

    /**
     * 包装Response转换
     *
     * @param res    原Response
     * @param mapper 转换方法
     * @param <T>    原Response包装类型
     * @param <R>    转换后Response包装类型
     * @return 转换后Response
     */
    public static <T, R> Response<R> map(Response<T> res, Function<? super T, ? extends R> mapper) {
        if (Objects.isNull(res) || Objects.isNull(res.getSuccess()) || !res.getSuccess()) {
            return Response.createError(res.getMsg());
        }
        return Response.createSuccess(mapper.apply(res.getData()));
    }


    /**
     * 捕获异常
     *
     * @param supplier supplier
     * @param <T>      t
     * @return t
     */
    public static <T> Response<T> or500(Supplier<T> supplier) {
        try {
            return Response.createSuccess(supplier.get());
        } catch (InternalServerException errorResponse) {
            log.info("fail, code: {},message:{}", errorResponse.getCode(), errorResponse.getMessage());
            return Response.createError(errorResponse.getCode(), errorResponse.getMessage());
        } catch (Exception var6) {
            log.error("error, cause: {}", Throwables.getStackTraceAsString(var6));
            return Response.createError(500, "内部异常");
        }
    }

    /**
     * 捕获异常
     *
     * @param supplier supplier
     * @param <T>      t
     * @return t
     */
    public static <T,R> Response<R> or500(Supplier<T> supplier, Function<? super T, ? extends R> mapper) {
        try {
            return Response.createSuccess(mapper.apply(supplier.get()));
        } catch (InternalServerException errorResponse) {
            log.info("fail, code: {},message:{}", errorResponse.getCode(), errorResponse.getMessage());
            return Response.createError(errorResponse.getCode(), errorResponse.getMessage());
        } catch (Exception var6) {
            log.error("error, cause: {}", Throwables.getStackTraceAsString(var6));
            return Response.createError(500, "内部异常");
        }
    }

}
